package pers.cz.jefconfig.resource;

import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @program: JefConfig
 * @description: 基于类加载器的资源加载
 * @author: Cheng Zhi
 * @create: 2022-07-15 11:12
 **/
public class ClassPathResourceLoader extends AbstractJefResourceLoader {

    private boolean isDirOnly = false;

    private List<ClassLoader> loaders;

    public ClassPathResourceLoader() {
        this(false);
    }

    public ClassPathResourceLoader(boolean isDirOnly) {

        this.isDirOnly = isDirOnly;
        setDefaultClassLoader();
    }

    /**
     * 指定查找资源的classpath使用默认的
     */
    public void setDefaultClassLoader(){
        ClassLoader cl=Thread.currentThread().getContextClassLoader();
        if(cl==null){
            cl= ClassPathResourceLoader.class.getClassLoader();
        }
        this.loaders= Arrays.asList(cl);
    }

    @Override
    public URL getResource(String name) {
        if (name.startsWith("/")) {
            name = name.substring(1);
        }

        if (isDirOnly) {
            name = "./" + name;
        }

        if(loaders!=null && loaders.size()>0){
            for(ClassLoader loader:loaders){
                URL res=loader.getResource(name);
                if(res!=null)return res;
            }
        }
        return null;
    }

    @Override
    public List<URL> getResources(String name) {
        if (name.startsWith("/")) {
            name = name.substring(1);
        }

        if (isDirOnly) {
            name = "./" + name;
        }

        Set<URL> result=new LinkedHashSet<URL>();
        try{
            if(loaders!=null && loaders.size()>0){
                for(ClassLoader loader:loaders){
                    for(Enumeration<URL> e=loader.getResources(name);e.hasMoreElements();){
                        result.add(e.nextElement());
                    }
                }
            }
        }catch(IOException e){
            throw new IllegalArgumentException(e.getMessage());
        }
        return new ArrayList<URL>(result);
    }
}
